import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import org.json.JSONObject;
import javax.servlet.annotation.WebServlet;

@WebServlet("/delete_book")
public class DeleteBook extends HttpServlet {

    private static final String URL = "jdbc:mysql://1.15.151.81:3306/linux_exam";
    private static final String USER = "root";
    private static final String PASSWORD = "1qaz@WSX#EDC";
    private static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");

        response.setContentType("application/json;charset=UTF-8");
        String number = request.getParameter("number");
        PrintWriter out = response.getWriter();

        JSONObject result = deleteBook(number);
        out.print(result.toString());
    }

    public JSONObject deleteBook(String number) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        JSONObject result = new JSONObject();
        try {
            Class.forName(DRIVER_CLASS);
            conn = DriverManager.getConnection(URL, USER, PASSWORD);

            String sql = "DELETE FROM t_book WHERE number = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, number);
            int deleted = pstmt.executeUpdate();

            if (deleted > 0) {
                result.put("status", "success");
                result.put("message", "Book deleted successfully.");
            } else {
                result.put("status", "error");
                result.put("message", "Book not found.");
            }
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "Error occurred: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try { if (pstmt != null) pstmt.close(); } catch (Exception e) { e.printStackTrace(); }
            try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); }
        }
        return result;
    }
}
